/*!
 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0
 */

import * as nodefs from 'fs' // eslint-disable-line no-restricted-imports
import * as path from 'path'

/**
 * Generate a settings type based on `package.json:contributes.configuration`.
 * It will create a settings-<subproject>.gen.ts file in the core lib which will
 * allow it to provide autocomplete and compile-time type checking of settings names.
 *
 * This script is meant to be run from individual from subprojects.
 */

function main() {
    const ext = path.basename(process.cwd())
    const packageJsonFile = './package.json'
    const packageJson = JSON.parse(nodefs.readFileSync(packageJsonFile, { encoding: 'utf-8' }))

    const genFile = `../core/src/shared/settings-${ext}.gen.ts`
    type Configuration = { [key: string]: { [key: string]: {} } }
    const settings: Configuration = {}

    Object.entries(packageJson.contributes.configuration.properties as { [key: string]: { properties?: {} } }).forEach(
        ([k, v]) => {
            settings[k] = {}
            if (v.properties !== undefined) {
                for (const inner of Object.keys(v.properties)) {
                    settings[k][inner] = {}
                }
            }
        }
    )

    const contents = `/*!
 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0
 */

/**
 * This file was autogenerated by generateSettings.ts. Do NOT modify by hand.
 * To update this file, update the settings in the extension package.json
 * and run \`npm run generateSettings\` for that extension.
 */

export const ${ext}Settings = ${JSON.stringify(settings, undefined, '    ')}

export default ${ext}Settings
`

    nodefs.writeFileSync(genFile, contents)
}

main()
